package com.hyjy.music.fragment

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.CompoundButton
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import com.hyjy.music.ContextHolder
import com.hyjy.music.R
import com.hyjy.music.TableLrcHelper
import com.hyjy.music.base.BaseDialogFragment
import com.hyjy.music.databinding.FragmentLrcSettingsBinding
import com.hyjy.music.util.*

/**
 * 歌词设置对话框
 */
class LrcSettingsFragment : BaseDialogFragment<FragmentLrcSettingsBinding>(),
    OnSeekBarChangeListener, View.OnClickListener {

    private var musicMainFragment: MainFragment? = null
    private lateinit var lrcColors: Array<String>
    private var textViews = mutableListOf<TextView?>()
    private var currentPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        musicMainFragment = parentFragment as MainFragment?
    }

    override fun initDialog(): Dialog {
        return Dialog(context!!, R.style.LrcSettingsDialog).apply {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCanceledOnTouchOutside(true)
            // 设置弹出框布局参数
            window?.let {
                val layoutParams = it.attributes
                layoutParams?.gravity = Gravity.BOTTOM
                layoutParams?.width = WindowManager.LayoutParams.MATCH_PARENT
                it.attributes = layoutParams
            }
        }
    }

    override fun initData() {
        lrcColors = resources.getStringArray(R.array.lrc_color)
        binding?.seekBar?.max = 7
        binding?.seekBar?.setOnSeekBarChangeListener(this)

        textViews.clear()
        // 不要改动add方法的位置
        textViews.add(binding?.tvWhite)
        textViews.add(binding?.tvBrown)
        textViews.add(binding?.tvGreen)
        textViews.add(binding?.tvPink)
        textViews.add(binding?.tvYellow)
        textViews.add(binding?.tvPurple)
        textViews.add(binding?.tvCyan)
        textViews.add(binding?.tvRed)

        binding?.ivWhite?.setOnClickListener(this)
        binding?.ivRed?.setOnClickListener(this)
        binding?.ivGreen?.setOnClickListener(this)
        binding?.ivPink?.setOnClickListener(this)
        binding?.ivYellow?.setOnClickListener(this)
        binding?.ivPurple?.setOnClickListener(this)
        binding?.ivCyan?.setOnClickListener(this)
        binding?.ivBrown?.setOnClickListener(this)
        // 桌面歌词开关
        binding?.switchLrc?.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
            if (!isChecked) {
                // 删除桌面歌词
                TableLrcHelper.removeLrcOnTable()
                return@setOnCheckedChangeListener
            }
            val hasPermission = PermissionHelper.checkFloatPermission(ContextHolder.context)
            if (hasPermission) {
                // 显示桌面歌词
                TableLrcHelper.showLrcOnTable()
                putBoolean(KEY_SWITCH_STATUS, true)
                // 桌面歌词信息只有LrcView知道,所以要绕这么一圈去调用
                musicMainFragment?.showTableLrc()
                return@setOnCheckedChangeListener
            }
            binding?.switchLrc?.isChecked = false
            showToast("桌面歌词需要悬浮窗权限")
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            startActivity(intent)
        }
        // 歌词匀速滚动开关
        binding?.switchRoll?.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
            musicMainFragment?.setUniform(isChecked)
            putBoolean(KEY_SWITCH_STATUS_ROLL, isChecked)
        }
        recoverLrcStatus()
    }

    override fun onProgressChanged(seekBar: SeekBar, progress: Int, b: Boolean) {
        if (b) {
            onLrcStatusChangedListener?.onLrcSizeStatusChange(progress)
        }
    }

    override fun onStartTrackingTouch(seekBar: SeekBar) {}
    override fun onStopTrackingTouch(seekBar: SeekBar) {
        val progress = seekBar.progress
        putInt(KEY_LRC_SIZE, progress)
    }

    override fun onClick(view: View) {
        onLrcStatusChangedListener?.run {
            // 获取xml文件里面定义的tag
            val tag = view.tag
            if (tag is String) {
                val clickPosition = tag.toInt()
                if (currentPosition == clickPosition) {
                    return
                }
                // 选中状态√显示出来,否则隐藏
                textViews[currentPosition]?.visibility = View.GONE
                currentPosition = clickPosition
                textViews[currentPosition]?.visibility = View.VISIBLE
                putInt(KEY_LRC_COLOR, clickPosition)
                val color = Color.parseColor(lrcColors[clickPosition])
                onLrcColorStatusChange(color)
            }
        }
    }

    private var onLrcStatusChangedListener: OnLrcStatusChangedListener? = null

    fun setOnLrcStatusChangedListener(listener: OnLrcStatusChangedListener?) {
        onLrcStatusChangedListener = listener
    }

    /**
     * 歌词状态改变的监听器
     */
    interface OnLrcStatusChangedListener {
        /**
         * 歌词颜色改变了
         *
         * @param color 改变后的颜色
         */
        fun onLrcColorStatusChange(color: Int)

        /**
         * 歌词大小改变了
         *
         * @param size 改变后的大小
         */
        fun onLrcSizeStatusChange(size: Int)
    }

    /**
     * 回显字体大小和颜色,桌面歌词状态
     */
    private fun recoverLrcStatus() {
        // 回显字体颜色(打钩的位置)
        val clickPosition = getInt(KEY_LRC_COLOR, 0)
        textViews[clickPosition]?.visibility = View.VISIBLE
        currentPosition = clickPosition
        // 回显字体大小(SeekBar的位置)
        val progress = getInt(KEY_LRC_SIZE, 0)
        binding?.seekBar?.progress = progress
        // 回显桌面歌词开关的状态
        val status = getBoolean(KEY_SWITCH_STATUS, false)
        binding?.switchLrc?.isChecked = status
        // 是否匀速滚动
        val uniform = getBoolean(KEY_SWITCH_STATUS_ROLL, false)
        binding?.switchRoll?.isChecked = uniform
    }
}